from flask import Flask
from flask_restful import Resource, Api, marshal_with, fields, marshal

# 普通类,假设是模型类
class User(object):
    def __init__(self, user_id, name, age):
        self.user_id = user_id
        self.name = name
        self.age = age

# 1.1先自定义想要返回的数据格式
my_fields = {
    'user_id': fields.Integer,
    'name': fields.String
}

app = Flask(__name__)
api = Api(app)

class Index(Resource):
    # 1.2 在使用marshal_with装饰器装饰
    # @marshal_with(my_fields, envelope='data')
    # def get(self):
    #     user = User(1, 'laowang', 18)
    #     return user

    # 2.marshal工具直接返回
    def get(self):
        user = User(1, 'laowang', 18)
        # {"data":{"user_id":1, "name":"laowang"}}
        return marshal(user, my_fields, envelope='data')

api.add_resource(Index, '/')

if __name__ == "__main__":
    app.run(debug=True,host='0.0.0.0', port=5000)
